package cn.org.hentai.jtt1078.util;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class JedisPoolUtil {

    private static volatile JedisPool jedisPool;

    private JedisPoolUtil() {
        // 防止被实例化
    }

    /**
     * 初始化JedisPool
     */
    public static synchronized void init(String host, int port, int timeout, String password, int database,
                                         JedisPoolConfig poolConfig) {
        if (jedisPool == null) {
            jedisPool = new JedisPool(poolConfig, host, port, timeout, password, database);
        }
    }

    /**
     * 获取Jedis实例
     */
    public static Jedis getJedis() {
        if (jedisPool == null) {
            throw new RuntimeException("JedisPool未初始化，请先调用init方法");
        }
        return jedisPool.getResource();
    }

    /**
     * 归还Jedis资源
     */
    public static void close(Jedis jedis) {
        if (jedis != null) {
            jedis.close();
        }
    }

    /**
     * 关闭JedisPool
     * 注意：此方法应在应用程序关闭时调用一次
     */
    public static void destroy() {
        if (jedisPool != null) {
            jedisPool.close();
            jedisPool = null;
        }
    }
}
